const api = require('../../../api/mop_api');
import { toast, log, err, to } from '../../../utils/wxapi';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    typelist: [],
    page: 1,
    size: 10,
    pageTotal: 0,
  },
  // 编辑
  edit(e) {
    const id = e.target.dataset.id;
    to('/dj/pages/addtype/addtype?id=' + id);
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.type();
  },
  async type() {
    try {
      const { page, size } = this.data;
      const res = await api.typelist({ page, size });
      if (res.respCode === 200) {
        let typelist = this.listsort(JSON.parse(res.source));
        log(typelist);
        if (this.data.typelist.length === 0) {
          this.setData({
            typelist,
            pageTotal: res.pageTotal,
          });
        } else {
          this.setData({
            typelist: this.data.typelist.concat(typelist),
            pageTotal: res.pageTotal,
          });
        }
      } else {
        toast(res.msg);
      }
    } catch (error) {
      err(error);
      throw error;
    }
  },
  listsort(arr) {
    arr.sort((a, b) => b.sort - a.sort);
    return arr;
  },
  toadd() {
    to('/dj/pages/addtype/addtype');
  },
  deltype(e) {
    try {
      const { id } = e.currentTarget.dataset;

      wx.showModal({
        title: '提示',
        content: '你确定删除该商品类型吗？',
        complete: async res => {
          if (res.confirm) {
            const res = await api.typedel({ id });
            if (res.respCode === 200) {
              toast('删除成功');
              this.setData({
                typelist: [],
                page: 1,
              });
              this.type();
            } else {
              toast(res.msg);
            }
          }
        },
      });
    } catch (error) {
      err(error);
      throw error;
    }
  },
  onHide() {
    this.setData({
      typelist: [],
      page: 1,
    });
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    let { typelist, pageTotal, page } = this.data;
    if (typelist.length < pageTotal) {
      this.setData({
        page: page + 1,
      });
      this.type();
    } else {
      toast('已加载全部数据');
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
